package web.login.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import web.commonApp.constants.CommonConstants;
import web.login.bo.ForgotPasswordBO;
import web.login.to.ForgotPassTo;

@Controller
@RequestMapping(value="/forgotPassword.htm")
public class ForgotPasswordController {

	private final Log log = LogFactory.getLog(ForgotPasswordController.class);
	
	@Autowired
	private ForgotPasswordBO forgotPasswordBO;
		
	public ForgotPasswordBO getForgotPasswordBO() {
		return forgotPasswordBO;
	}

	public void setForgotPasswordBO(ForgotPasswordBO forgotPasswordBO) {
		this.forgotPasswordBO = forgotPasswordBO;
	}

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView onLoad(HttpServletRequest request) 
	{
		log.info("INSIDE ForgotPasswordController onLoad METHOD");
		ForgotPassTo forgotPassTo=new ForgotPassTo();
		ModelAndView mav = new ModelAndView("forgotPassword");
		mav.addObject("forgotPassTo",forgotPassTo);
		return mav;
	}
	
	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView onSubmit(@ModelAttribute("forgotPassTo")ForgotPassTo forgotPassTo,HttpServletRequest request) 
	{
		log.info("INSIDE ForgotPasswordController onSubmit METHOD");
		boolean status = false;
		String userName = forgotPassTo.getUserName();
		final String senderMail = (String)request.getServletContext().getAttribute("SENDER_EMAIL");
		final String senderPass = (String)request.getServletContext().getAttribute("SENDER_PASS");

		log.info("Got sender mail : "+senderMail+" and password: "+senderPass+" from the servletContext");
		
		if(userName != null)
		{
			status = forgotPasswordBO.getUserDetailsAndMail(userName,senderMail,senderPass);
		}
		
		Map<String, String> map= new HashMap<String, String>();
		if(status == false)
			map.put(CommonConstants.FORGOT_PASS_STATUS_MSG,"Password could not be sent.");
		else
			map.put(CommonConstants.FORGOT_PASS_STATUS_MSG,"Password mail sent.");
		
		return new ModelAndView(new RedirectView("login.htm"),map);
	}
}
